<template>
  <div>
    <el-card>
      <el-form :model="updPwdForm"
               label-position="right"
               :rules="updPwdFormRules"
               ref="updPwdFormRef"
               label-width="150px">
        <el-form-item label="邮箱">
          <el-input v-model="updPwdForm.umail" disabled></el-input>
        </el-form-item>
        <el-form-item label="请输入新密码" prop="upwd">
          <el-input placeholder="请输入新密码" v-model="updPwdForm.upwd"
                    prefix-icon="iconfont icon-3702mima"
                    type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="请再次输入新密码" prop="checkPass">
          <el-input placeholder="请再次输入新密码" v-model="updPwdForm.checkPass"
                    prefix-icon="iconfont icon-3702mima"
                    type="password" show-password></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="doUpd">修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data(){
    let validatePass = (rules, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          if (this.updPwdForm.checkPass !== '') {
              this.$refs.updPwdFormRef.validateField('checkPass');
          }
          callback();
        }
      };
      let validatePass2 = (rules, value, callback) => {
        if (value === '') {
            callback(new Error('请再次输入密码'));
        } else if (value !== this.updPwdForm.upwd) {
            callback(new Error('两次输入密码不一致!'));
        } else {
            callback();
        }
      };
    return {
      updPwdForm: {
        userId: window.sessionStorage.getItem('loginUserId'),
        umail: window.sessionStorage.getItem('loginUserUmail'),
        upwd:'',
        checkPass: ''
      },
      updPwdFormRules:{
        upwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 9,  message: '长度在 6 到 9 个字符', trigger: 'blur', },
          { validator: validatePass, trigger: 'blur' }     
        ],
        //验证密码是否合法
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur', required: true } 
        ], 
      }
    }
  },
  methods: {
    async doUpd(){
      let url = 'admin/user/updateUser/';
      let param = this.updPwdForm;
      const { data: res } = await this.$axios.put(url, param);
      if (res.code !== 200) {
        return this.$message.error('更新密码失败！');
      }
      this.$message.success('更改密码成功,请重新登录！');
      this.$router.push('/login');
    }
  }
}
</script>

<style scoped>
.btns {
  margin-left: 40%;
}
</style>